import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.File;

public class HttpServer {

    public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator  + "webroot";
    
    private static final String KILL_COMMAND = "/KILL";
    private boolean kill = false;

    public static void main(String[] args) {
	HttpServer server = new HttpServer();
	server.await();
    }

    public void await() {
	ServerSocket serverSocket = null;
	try {
	    serverSocket =  new ServerSocket(8080, 1, InetAddress.getByName("127.0.0.1"));
	}
	catch (IOException e) {
	    e.printStackTrace();
	    System.exit(1);
	}
	
	while (!kill) {
	    Socket socket = null;
	    InputStream input = null;
	    OutputStream output = null;
	    byte[] outBytes = new byte[1024];
	    try {
		socket = serverSocket.accept();
		input = socket.getInputStream();
		output = socket.getOutputStream();
		
		RequestAction request = new RequestAction(input);
		request.parse();

		ResponseAction response = new ResponseAction(output);
		response.setRequest(request);
		response.send();

		//FileManagement manager = new FileManagement("webroot/");
		//output = manager.getFile("index.htm");
		//outBytes = manager.getFile("index.htm1", output);
		//System.out.println(output);

		socket.close();
		
		kill = request.getURI().equals(KILL_COMMAND);
	    }
	    catch (Exception e) {
		e.printStackTrace();
		continue;
	    }
	}
    }
}
